package zyh.listener;

import zyh.servlet.DbDao;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;

//@WebListener
public class OnlListener implements ServletContextListener {
    public final int MAX_MILLIS=10*60*1000;
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        new javax.swing.Timer(1000 * 5, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try
                {
                    DbDao dd = new DbDao("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/1613580003",
                            "root", "123456");
                    ResultSet rs = dd.query("select * from online_inf", false);
                    StringBuffer beRemove=new StringBuffer("(");
                    while (rs.next())
                    {
                        if((System.currentTimeMillis()-rs.getLong(5))>MAX_MILLIS)
                        {
                            beRemove.append("'");
                            beRemove.append(rs.getString(1));
                            beRemove.append("'  ,");
                        }
                    }
                    if(beRemove.length()>3)
                    {
                        beRemove.setLength(beRemove.length()-3);
                        beRemove.append(")");
                        dd.modify("delete from online_inf where session_id in" +beRemove.toString());
                    }dd.closeConn();
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
